import axios from 'axios-miniprogram';
import { Config } from '../config.js'; // 导入配置文件

const { LOCAL_SERVICE, COZE } = Config;

// 创建本地服务实例
const instance = axios.create({
  baseURL: LOCAL_SERVICE.BASE_URL,
  method: 'GET',
  timeout: 5000,
  headers: {'Content-Type': 'application/json'}
});

// 请求拦截器 - 本地服务
instance.interceptors.request.use(
  config => {
    if (!['/usser/login', '/user/register'].includes(config.url)) {
			const token = wx.getStorageSync('token');
			console.log(config)
      if (token) config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

instance.interceptors.response.use(
  response => {
    // 直接返回data，自动去掉外层包装
    return response.data;
  },
  error => {
    // 处理错误
    return Promise.reject(error);
  }
);

// 创建扣子智能体API实例
const cozeInstance = axios.create({
  baseURL: COZE.API_BASE_URL,
  method: 'POST',
  timeout: 10000, // 延长超时时间
  headers: {'Content-Type': 'application/json'}
});

// 请求拦截器 - 扣子API
cozeInstance.interceptors.request.use(
  config => {
    config.headers.Authorization = `Bearer ${COZE.ACCESS_TOKEN}`;
    return config;
  },
  error => {
    wx.showToast({ title: '请求失败，请检查网络', icon: 'none' });
    return Promise.reject(error);
  }
);

// 响应拦截器 - 统一错误处理
cozeInstance.interceptors.response.use(
  response => response.data,
  error => {
    const msg = error.response?.data?.msg || '服务异常，请稍后重试';
    wx.showToast({ title: msg, icon: 'none' });
    return Promise.reject(error);
  }
);

export default instance;
export { cozeInstance };